package com.lagou.oauth.config;

import com.lagou.user.api.UserRemoteService;
import com.lagou.user.api.dto.UserDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.DefaultAccessTokenConverter;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Component
public class LagouAccessTokenConvertor extends DefaultAccessTokenConverter {

    @Autowired
    UserRemoteService userRemoteService;

    @Override
    public Map<String, ?> convertAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication) {
        HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.getRequestAttributes())).getRequest();
        //获取客户端ip
        String remoteAddr = request.getRemoteAddr();
        Map<String, Object> convertMap = (Map<String, Object>) super.convertAccessToken(token, authentication);
        convertMap.put("clientIp", remoteAddr);
        UserDTO user = userRemoteService.getUserByPhone(convertMap.get("user_name").toString());
        if (null != user){
            convertMap.put("user_id",user.getId());
        }
            return convertMap;
    }
}
